<template>
  <div class="box">
    <h3>
      批量导入
    </h3>
    <myexcel :beforeUpload="beforeUpload" :onSuccess="onSuccess"></myexcel>
  </div>
</template>

<script>
import { addEmployeesListApi } from '@/api/employees'
import moment from 'moment'
export default {
  name: 'excel',
  methods: {
    beforeUpload (file) {
      const less2M = file.size < 2 * 1024 * 1024
      if (!less2M) {
        this.$message.error('文件大小超过2m')
      }
      return less2M
    },
    async onSuccess({header,results}){
        const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      const newArr = results.map(item => {
          const newObj = {}
          Object.keys(obj).forEach(subitem=>{
              if(subitem === '入职日期' || subitem === '转正日期'){
                  newObj[obj[subitem]] = this.formDate(item[subitem])
              }else{
                  newObj[obj[subitem]] = item[subitem]
              }
          })
          return newObj
      })
    console.log(newArr);
    await addEmployeesListApi(newArr)
    this.$message.success('批量导入成功')
    this.$router.push('/employees')
    },
    formDate(date){
        const time = (date - 1) *24*60*60*1000
        let myDate = new Date(time)
        myDate.setFullYear(myDate.getFullYear() - 70)
        myDate = moment(myDate).format('YYYY-MM-DD')
        return myDate        
    }
  }
}
</script>

<style lang="scss">
.box {
  h3 {
    text-align: center;
  }
}
</style>
